﻿Imports System
Imports System.Collections.Generic
Imports System.ComponentModel
Imports System.Text
Imports System.Web
Imports System.Web.UI
Imports System.Web.UI.WebControls
Imports System.Text.RegularExpressions
Imports System.Xml

Namespace DotNetNuke.Modules.ActiveForums.Controls
    <DefaultProperty("Text"), ToolboxData("<{0}:TopicsView runat=server></{0}:TopicsView>")> _
    Public Class TopicsView
        Inherits ForumBase
#Region "Private Members"
        Private _metaTemplate As String = "[META][TITLE][PORTALNAME] - [PAGENAME] - [GROUPNAME] - [FORUMNAME][/TITLE][DESCRIPTION][BODY][/DESCRIPTION][KEYWORDS][VALUE][/KEYWORDS][/META]"
        Private _metaTitle As String = String.Empty
        Private _metaDescription As String = String.Empty
        Private _metaKeywords As String = String.Empty
        Private ForumName As String
        Private GroupName As String
        'Private ForumGroupId As Integer = 0
        'Private TopicsTemplateId As Integer
        Private drForum As DataRow
        Private drSecurity As DataRow
        Private dtTopics As DataTable
        Private dtAnnounce As DataTable
        Private dtSubForums As DataTable
        Private bView As Boolean = False
        Private bRead As Boolean = False
        Private bReply As Boolean = False
        Private bCreate As Boolean = False
        Private bPoll As Boolean = False
        Private bDelete As Boolean = False
        Private bEdit As Boolean = False
        Private bLock As Boolean = False
        Private bPin As Boolean = False
        Private bSubscribe As Boolean = False
        Private bModApprove As Boolean = False
        Private bModMove As Boolean = False
        Private bModSplit As Boolean = False
        Private bModDelete As Boolean = False
        Private bModEdit As Boolean = False
        Private bModLock As Boolean = False
        Private bModPin As Boolean = False
        Private bAllowRSS As Boolean = False
        Private RowIndex As Integer = 1
        Private PageSize As Integer = 20
        Private TopicRowCount As Integer = 0
        Private MyTheme As String = "_default"
        Private MyThemePath As String = String.Empty
        Private LastReplySubjectReplaceTag As String = String.Empty
        Private IsSubscribedForum As Boolean = False
        Private sGroupURL As String = String.Empty
        Private sForumURL As String = String.Empty
#End Region
#Region "Public Properties"
        Public Property MetaTemplate() As String
            Get
                Return _metaTemplate
            End Get
            Set(ByVal value As String)
                _metaTemplate = value
            End Set
        End Property
        Public Property MetaTitle() As String
            Get
                Return _metaTitle
            End Get
            Set(ByVal value As String)
                _metaTitle = value
            End Set
        End Property
        Public Property MetaDescription() As String
            Get
                Return _metaDescription
            End Get
            Set(ByVal value As String)
                _metaDescription = value
            End Set
        End Property
        Public Property MetaKeywords() As String
            Get
                Return _metaKeywords
            End Get
            Set(ByVal value As String)
                _metaKeywords = value
            End Set
        End Property
        Public Property ForumUrl() As String = String.Empty
#End Region
#Region "Controls"
        Protected WithEvents ctlForumJump As New DotNetNuke.Modules.ActiveForums.af_quickjump
        'Protected WithEvents cbActions As New DotNetNuke.Modules.ActiveForums.Controls.Callback
        Protected WithEvents ctlModal As New DotNetNuke.Modules.ActiveForums.Controls.Modal
        Protected WithEvents ctlForumSubs As New DotNetNuke.Modules.ActiveForums.Controls.ForumView

#End Region

        Private Sub Page_Init(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Init

        End Sub

        Private Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
            Try
                If ForumId < 1 Then
                    Response.Redirect(NavigateUrl(TabId))
                End If
                If ForumInfo Is Nothing Then
                    Response.Redirect(NavigateUrl(TabId))
                End If
                If ForumInfo.Active = False Then
                    Response.Redirect(NavigateUrl(TabId))
                End If
                Me.AppRelativeVirtualPath = "~/"
                MyTheme = MainSettings.Theme
                MyThemePath = Page.ResolveUrl("~/DesktopModules/ActiveForums/themes/" & MyTheme)
                Dim defaultTemplateId As Integer = ForumInfo.TopicsTemplateId
                If DefaultTopicsViewTemplateId >= 0 Then
                    defaultTemplateId = DefaultTopicsViewTemplateId
                End If
                Dim TopicsTemplate As String = String.Empty
                If UseTemplatePath And Not TemplatePath = String.Empty Then
                    TopicsTemplate = Utilities.GetFileContent(TemplatePath & "TopicsView.htm")
                    TopicsTemplate = Utilities.ParseSpacer(TopicsTemplate)
                Else
                    TopicsTemplate = DataCache.GetCachedTemplate(MainSettings.TemplateCache, ModuleId, "TopicsView", defaultTemplateId)
                End If
                Dim loadComplete As Boolean = False
                If TopicsTemplate.Contains("[NOTOOLBAR]") Then
                    If HttpContext.Current.Items.Contains("ShowToolbar") Then
                        HttpContext.Current.Items("ShowToolbar") = False
                    Else
                        HttpContext.Current.Items.Add("ShowToolbar", False)
                    End If
                    TopicsTemplate = TopicsTemplate.Replace("[NOTOOLBAR]", String.Empty)
                End If
                TopicsTemplate = TopicsTemplate.Replace("[PORTALID]", PortalId.ToString)
                TopicsTemplate = TopicsTemplate.Replace("[MODULEID]", ForumModuleId.ToString)
                TopicsTemplate = TopicsTemplate.Replace("[TABID]", ForumTabId.ToString)
                TopicsTemplate = TopicsTemplate.Replace("[AF:CONTROL:FORUMID]", ForumId.ToString)
                TopicsTemplate = TopicsTemplate.Replace("[AF:CONTROL:FORUMGROUPID]", ForumGroupId.ToString)
                TopicsTemplate = TopicsTemplate.Replace("[AF:CONTROL:PARENTFORUMID]", ParentForumId.ToString)
   
                PageSize = MainSettings.PageSize
                If UserId > 0 Then
                    PageSize = UserDefaultPageSize
                End If
                If PageSize < 5 Then
                    PageSize = 10
                End If

                If PageId = 1 Then
                    RowIndex = 0
                Else
                    RowIndex = ((PageId * PageSize) - PageSize)
                End If
                Dim sort As String = SortColumns.ReplyCreated
                If TopicsTemplate.Contains("[AF:SORT:TOPICCREATED]") Then
                    sort = SortColumns.TopicCreated
                    TopicsTemplate = TopicsTemplate.Replace("[AF:SORT:TOPICCREATED]", String.Empty)
                End If
                TopicsTemplate = CheckControls(TopicsTemplate)
   
                TopicsTemplate = TopicsTemplate.Replace("[AF:SORT:REPLYCREATED]", String.Empty)
                If TopicsTemplate.Contains("[TOPICS]") Then
                    Dim ds As DataSet = DataProvider.Instance.UI_TopicsView(PortalId, ModuleId, ForumId, UserId, RowIndex, PageSize, UserInfo.IsSuperUser, sort)
                    If ds.Tables.Count > 0 Then
                        drForum = ds.Tables(0).Rows(0)
                        drSecurity = ds.Tables(1).Rows(0)
                        dtSubForums = ds.Tables(2)
                        dtTopics = ds.Tables(3)
                        If PageId = 1 Then
                            dtAnnounce = ds.Tables(4)
                        End If

                        bView = Permissions.HasPerm(drSecurity("CanView").ToString, ForumUser.UserRoles)
                        bRead = Permissions.HasPerm(drSecurity("CanRead").ToString, ForumUser.UserRoles)
                        bCreate = Permissions.HasPerm(drSecurity("CanCreate").ToString, ForumUser.UserRoles)
                        bEdit = Permissions.HasPerm(drSecurity("CanEdit").ToString, ForumUser.UserRoles)
                        bDelete = Permissions.HasPerm(drSecurity("CanDelete").ToString, ForumUser.UserRoles)
                        bReply = Permissions.HasPerm(drSecurity("CanReply").ToString, ForumUser.UserRoles)
                        bPoll = Permissions.HasPerm(drSecurity("CanPoll").ToString, ForumUser.UserRoles)

                        bSubscribe = Permissions.HasPerm(drSecurity("CanSubscribe").ToString, ForumUser.UserRoles)
                        bModMove = Permissions.HasPerm(drSecurity("CanModMove").ToString, ForumUser.UserRoles)
                        bModSplit = Permissions.HasPerm(drSecurity("CanModSplit").ToString, ForumUser.UserRoles)
                        bModDelete = Permissions.HasPerm(drSecurity("CanModDelete").ToString, ForumUser.UserRoles)
                        bModApprove = Permissions.HasPerm(drSecurity("CanModApprove").ToString, ForumUser.UserRoles)
                        bModEdit = Permissions.HasPerm(drSecurity("CanModEdit").ToString, ForumUser.UserRoles)
                        bModPin = Permissions.HasPerm(drSecurity("CanModPin").ToString, ForumUser.UserRoles)
                        bModLock = Permissions.HasPerm(drSecurity("CanModLock").ToString, ForumUser.UserRoles)
                        bModApprove = Permissions.HasPerm(drSecurity("CanModApprove").ToString, ForumUser.UserRoles)

                        Dim ctlUtils As New ControlUtils
                        sGroupURL = ctlUtils.BuildUrl(ForumTabId, ForumModuleId, ForumInfo.ForumGroup.PrefixURL, String.Empty, ForumInfo.ForumGroupId, -1, -1, -1, String.Empty, 1, SocialGroupId)
                        sForumURL = ctlUtils.BuildUrl(ForumTabId, ForumModuleId, ForumInfo.ForumGroup.PrefixURL, ForumInfo.PrefixURL, ForumInfo.ForumGroupId, ForumInfo.ForumID, -1, -1, String.Empty, 1, SocialGroupId)
                        If bView Then
                            ForumName = drForum("ForumName").ToString
                            GroupName = drForum("GroupName").ToString
                            ForumGroupId = CInt(drForum("ForumGroupId"))
                            'TopicsTemplateId = CInt(drForum("TopicsTemplateId"))
                            bAllowRSS = CBool(drForum("AllowRSS"))
                            If bRead = False Then
                                bAllowRSS = False
                            End If
                            TopicRowCount = CInt(drForum("TopicRowCount"))
                            If UserId > 0 Then
                                IsSubscribedForum = CBool(IIf(CInt(drForum("IsSubscribedForum")) > 0, True, False))
                            End If
                            If MainSettings.UseSkinBreadCrumb Then
                                Environment.UpdateBreadCrumb(Page.Controls, "<a href=""" & sGroupURL & """>" & GroupName & "</a>")
                                TopicsTemplate = TopicsTemplate.Replace("<div class=""afcrumb"">[FORUMMAINLINK] > [FORUMGROUPLINK]</div>", String.Empty)
                            End If
                            If TopicsTemplate.Contains("[META]") Then
                                MetaTemplate = TemplateUtils.GetTemplateSection(TopicsTemplate, "[META]", "[/META]")
                                TopicsTemplate = TemplateUtils.ReplaceSubSection(TopicsTemplate, String.Empty, "[META]", "[/META]")
                            End If
                            'Parse Meta Template
                            If Not String.IsNullOrEmpty(MetaTemplate) Then
                                MetaTemplate = MetaTemplate.Replace("[FORUMNAME]", ForumName)
                                MetaTemplate = MetaTemplate.Replace("[GROUPNAME]", GroupName)
                                Dim pageName As String = String.Empty
                                Dim settings As DotNetNuke.Entities.Portals.PortalSettings = DotNetNuke.Entities.Portals.PortalController.GetCurrentPortalSettings
                                If (settings.ActiveTab.Title.Length = 0) Then
                                    pageName = Server.HtmlEncode(settings.ActiveTab.TabName)
                                Else
                                    pageName = Server.HtmlEncode(settings.ActiveTab.Title)
                                End If
                                MetaTemplate = MetaTemplate.Replace("[PAGENAME]", pageName)
                                MetaTemplate = MetaTemplate.Replace("[PORTALNAME]", settings.PortalName)
                                MetaTemplate = MetaTemplate.Replace("[TAGS]", String.Empty)
                                If MetaTemplate.Contains("[TOPICSUBJECT:") Then
                                    Dim pattern As String = "(\[TOPICSUBJECT:(.+?)\])"
                                    Dim regExp As New Regex(pattern)
                                    Dim matches As MatchCollection
                                    matches = regExp.Matches(MetaTemplate)
                                    For Each m As Match In matches
                                        MetaTemplate = MetaTemplate.Replace(m.Value, String.Empty)
                                    Next m
                                End If
                                MetaTemplate = MetaTemplate.Replace("[TOPICSUBJECT]", String.Empty)
                                If MetaTemplate.Contains("[BODY:") Then
                                    Dim pattern As String = "(\[BODY:(.+?)\])"
                                    Dim regExp As New Regex(pattern)
                                    Dim matches As MatchCollection
                                    matches = regExp.Matches(MetaTemplate)
                                    For Each m As Match In matches
                                        Dim iLen As Integer = CInt(m.Groups(2).Value)
                                        If ForumInfo.ForumDesc.Length > iLen Then
                                            MetaTemplate = MetaTemplate.Replace(m.Value, ForumInfo.ForumDesc.Substring(0, iLen) & "...")
                                        Else
                                            MetaTemplate = MetaTemplate.Replace(m.Value, ForumInfo.ForumDesc)
                                        End If
                                    Next m
                                End If
                                MetaTemplate = MetaTemplate.Replace("[BODY]", Utilities.StripHTMLTag(ForumInfo.ForumDesc))

                                MetaTitle = TemplateUtils.GetTemplateSection(MetaTemplate, "[TITLE]", "[/TITLE]").Replace("[TITLE]", String.Empty).Replace("[/TITLE]", String.Empty)
                                MetaDescription = TemplateUtils.GetTemplateSection(MetaTemplate, "[DESCRIPTION]", "[/DESCRIPTION]").Replace("[DESCRIPTION]", String.Empty).Replace("[/DESCRIPTION]", String.Empty)
                                MetaKeywords = TemplateUtils.GetTemplateSection(MetaTemplate, "[KEYWORDS]", "[/KEYWORDS]").Replace("[KEYWORDS]", String.Empty).Replace("[/KEYWORDS]", String.Empty)
                            End If
                            BindTopics(TopicsTemplate)
                        Else
                            Response.Redirect(NavigateUrl(TabId), True)
                        End If

                        Try
                            Environment.UpdateMeta(Me.BasePage, MetaTitle, MetaDescription, MetaKeywords)
                        Catch ex As Exception

                        End Try
                    Else
                        Response.Redirect(NavigateUrl(TabId), True)
                    End If
                    If Not Session("modal_View") Is Nothing Then
                        LoadModal(Session("modal_View").ToString, Session("modal_options").ToString)
                    End If
                Else
                    Dim fc As New ForumController
                    Dim fs As String = fc.GetForumsForUser(ForumUser.UserRoles, PortalId, ModuleId, "CanEdit")
                    If Not String.IsNullOrEmpty(fs) Then
                        bModEdit = True
                    End If
                    TopicsTemplate = ParseControls(TopicsTemplate)
                    TopicsTemplate = Utilities.LocalizeControl(TopicsTemplate)
                    Me.Controls.Add(Me.ParseControl(TopicsTemplate))
                    LinkControls(Me.Controls)
                End If
                



            Catch exc As Exception
                RenderMessage("[RESX:Error:LoadingTopics]", exc.Message, exc)
            End Try
        End Sub
        Private Sub BindTopics(ByVal TopicsTemplate As String)
            Dim sOutput As String = TopicsTemplate
            Dim subTemplate As String = String.Empty

            'Subforum Template

            If sOutput.Contains("[SUBFORUMS]") Then
                If dtSubForums.Rows.Count > 0 Then
                    subTemplate = TemplateUtils.GetTemplateSection(sOutput, "[SUBFORUMS]", "[/SUBFORUMS]")
                End If
                sOutput = TemplateUtils.ReplaceSubSection(sOutput, "<asp:placeholder id=""plhSubForums"" runat=""server"" />", "[SUBFORUMS]", "[/SUBFORUMS]")
            End If

            'Parse Common Controls
            sOutput = ParseControls(sOutput)
            'Parse Topics
            sOutput = ParseTopics(sOutput, dtTopics, "TOPICS")
            'Parse Announce
            Dim sAnnounce As String = TemplateUtils.GetTemplateSection(sOutput, "[ANNOUNCEMENTS]", "[/ANNOUNCEMENTS]")
            If Not dtAnnounce Is Nothing Then
                If dtAnnounce.Rows.Count > 0 Then
                    sAnnounce = ParseTopics(sAnnounce, dtAnnounce, "ANNOUNCEMENT")
                Else
                    sAnnounce = String.Empty
                End If
            Else
                sAnnounce = String.Empty
            End If
            sOutput = TemplateUtils.ReplaceSubSection(sOutput, sAnnounce, "[ANNOUNCEMENTS]", "[/ANNOUNCEMENTS]")

            sOutput = Utilities.LocalizeControl(sOutput)
            Me.Controls.Add(Me.ParseControl(sOutput))
            BuildPager()

            Dim plh As PlaceHolder = CType(Me.FindControl("plhQuickJump"), PlaceHolder)
            If Not plh Is Nothing Then
                ctlForumJump = New af_quickjump
                ctlForumJump.MOID = ModuleId
                ctlForumJump.dtForums = Nothing
                ctlForumJump.ModuleConfiguration = Me.ModuleConfiguration
                ctlForumJump.ForumId = ForumId
                ctlForumJump.ModuleId = ModuleId
                If ForumId > 0 Then
                    ctlForumJump.ForumInfo = ForumInfo
                End If
                plh.Controls.Add(ctlForumJump)
            End If
           
            plh = CType(Me.FindControl("plhSubForums"), PlaceHolder)
            If Not plh Is Nothing Then
                ctlForumSubs = CType(LoadControl(GetType(ForumView), Nothing), ForumView)
                ctlForumSubs.ModuleConfiguration = Me.ModuleConfiguration
                ctlForumSubs.ForumId = ForumId
                ctlForumSubs.ForumTable = dtSubForums
                ctlForumSubs.ForumTabId = ForumTabId
                ctlForumSubs.ForumModuleId = ForumModuleId
                ctlForumSubs.SubsOnly = True
                ctlForumSubs.DisplayTemplate = subTemplate
                If ForumId > 0 Then
                    ctlForumSubs.ForumInfo = ForumInfo
                End If
                plh.Controls.Add(ctlForumSubs)
            End If
            'Me.Controls.Add(cbActions)
            Me.Controls.Add(ctlModal)
            ' LoadCallBackScripts()
        End Sub
        Private Sub LinkControls(ByVal ctrls As ControlCollection)
            For Each ctrl As Control In ctrls
                If TypeOf (ctrl) Is ForumBase Then
                    DirectCast(ctrl, ForumBase).ModuleConfiguration = Me.ModuleConfiguration

                End If
                If ctrl.Controls.Count > 0 Then
                    LinkControls(ctrl.Controls)
                End If
            Next
        End Sub
        Private Function ParseControls(ByVal Template As String) As String
            Dim MyTheme As String = MainSettings.Theme
            Dim sOutput As String = Template
            sOutput = "<%@ Register TagPrefix=""ac"" Namespace=""DotNetNuke.Modules.ActiveForums.Controls"" Assembly=""DotNetNuke.Modules.ActiveForums"" %>" & sOutput

            'Forum Drop Downlist
            sOutput = sOutput.Replace("[JUMPTO]", "<asp:placeholder id=""plhQuickJump"" runat=""server"" />")
            'Tag Cloud
            sOutput = sOutput.Replace("[AF:CONTROLS:TAGCLOUD]", "<ac:tagcloud instanceid=""" & ModuleId & """ siteid=""" & PortalId & """ tabid=""" & TabId & """ runat=""server"" />")
            'Forum Subscription Control
            If bSubscribe Then
                Dim subControl As New Controls.ToggleSubscribe(0, ForumId, -1)
                subControl.Checked = IsSubscribedForum
                subControl.Text = "[RESX:ForumSubscribe:" & IsSubscribedForum.ToString.ToUpper & "]"
                sOutput = sOutput.Replace("[FORUMSUBSCRIBE]", subControl.Render())
            Else
                sOutput = sOutput.Replace("[FORUMSUBSCRIBE]", String.Empty)
            End If
            If Request.IsAuthenticated Then
                sOutput = sOutput.Replace("[MARKFORUMREAD]", "<am:MarkForumRead EnableViewState=""False"" id=""amMarkForumRead"" MID=""" & ForumModuleId & """ runat=""server"" />")
            Else
                sOutput = sOutput.Replace("[MARKFORUMREAD]", String.Empty)
            End If

            If bCreate Then
                Dim Params() As String = {}
                If SocialGroupId <= 0 Then
                    Params = {ParamKeys.ViewType & "=post", ParamKeys.ForumId & "=" & ForumId}
                Else
                    Params = {"GroupId=" & SocialGroupId, ParamKeys.ViewType & "=post", ParamKeys.ForumId & "=" & ForumId}
                End If
                sOutput = sOutput.Replace("[ADDTOPIC]", "<a href=""" & NavigateUrl(TabId, "", Params) & """ class=""dnnPrimaryAction"">[RESX:AddTopic]</a>")
            Else
                sOutput = sOutput.Replace("[ADDTOPIC]", "<div class=""amnormal"">[RESX:NotAuthorizedTopic]</div>")
            End If
                sOutput = sOutput.Replace("[ADDPOLL]", String.Empty)
                Dim Url As String
                If bAllowRSS Then

                    Url = DotNetNuke.Common.AddHTTP(DotNetNuke.Common.GetDomainName(Request)) & "/DesktopModules/ActiveForums/feeds.aspx?portalid=" & PortalId & "&forumid=" & ForumId & "&tabid=" & TabId & "&moduleid=" & ForumModuleId
                    If Not Request.QueryString("asg") Is Nothing Then
                        If IsNumeric(Request.QueryString("asg")) Then
                            Url &= "&asg=" & Request.QueryString("asg")
                        End If
                End If
                If SocialGroupId > 0 Then
                    Url &= "&GroupId=" & SocialGroupId
                End If
                    sOutput = sOutput.Replace("[RSSLINK]", "<a href=""" & Url & """><img src=""" & MyThemePath & "/images/rss.png"" border=""0"" alt=""[RESX:RSS]"" /></a>")
                Else
                    sOutput = sOutput.Replace("[RSSLINK]", String.Empty)
                End If
                If Request.IsAuthenticated Then
                    Url = NavigateUrl(TabId, "", New String() {ParamKeys.ViewType & "=sendto", ParamKeys.ForumId & "=" & ForumId, ParamKeys.TopicId & "=" & TopicId})
                    sOutput = sOutput.Replace("[AF:CONTROL:EMAIL]", "<a href=""" & Url & """ rel=""nofollow""><img src=""" & MyThemePath & "/images/email16.png"" border=""0"" alt=""[RESX:EmailThis]"" /></a>")
                Else
                    sOutput = sOutput.Replace("[AF:CONTROL:EMAIL]", String.Empty)
                End If
                If sOutput.Contains("[AF:CONTROL:ADDTHIS") Then
                    Dim strHost As String = DotNetNuke.Common.AddHTTP(DotNetNuke.Common.GetDomainName(Request))
                    sOutput = TemplateUtils.ParseSpecial(sOutput, SpecialTokenTypes.AddThis, strHost & Request.RawUrl, ForumName, bRead, MainSettings.AddThisAccount)
                End If
                sOutput = sOutput.Replace("[MINISEARCH]", "<am:MiniSearch  EnableViewState=""False"" id=""amMiniSearch"" MID=""" & ModuleId & """ FID=""" & ForumId & """ runat=""server"" />")
                sOutput = sOutput.Replace("[PAGER1]", "<am:pagernav id=""Pager1""  EnableViewState=""False"" runat=""server"" />")
                sOutput = sOutput.Replace("[PAGER2]", "<am:pagernav id=""Pager2"" runat=""server"" EnableViewState=""False"" />")
                If sOutput.Contains("[PARENTFORUMLINK]") Then
                    If ForumInfo.ParentForumId > 0 Then
                        sOutput = sOutput.Replace("[PARENTFORUMLINK]", "<a href=""" & Utilities.NavigateUrl(TabId) & """>" & ForumInfo.ParentForumName & "</a>")
                    ElseIf ForumInfo.ForumGroupId > 0 Then
                        sOutput = sOutput.Replace("[PARENTFORUMLINK]", "<a href=""" & Utilities.NavigateUrl(TabId) & """>" & ForumInfo.GroupName & "</a>")
                    End If
                End If
                ' If String.IsNullOrEmpty(ForumInfo.ParentForumName) Then
                sOutput = sOutput.Replace("[PARENTFORUMNAME]", ForumInfo.ParentForumName)
                'End If

                sOutput = sOutput.Replace("[FORUMMAINLINK]", "<a href=""" & NavigateUrl(TabId) & """>[RESX:ForumMain]</a>")
                sOutput = sOutput.Replace("[FORUMGROUPLINK]", "<a href=""" & sGroupURL & """>" & GroupName & "</a>")

                sOutput = sOutput.Replace("[FORUMNAME]", ForumName)
                sOutput = sOutput.Replace("[FORUMID]", ForumId.ToString)
                sOutput = sOutput.Replace("[GROUPNAME]", GroupName)
                If bModDelete Then
                    sOutput = sOutput.Replace("[ACTIONS:DELETE]", "<img onclick=""amaf_modDel([TOPICID]);"" src=""" & ImagePath & "/images/topic_delete.gif"" border=""0"" style=""vertical-align:middle;"" alt=""[RESX:DeleteTopic]"" style=""cursor:pointer;"" />")
                Else
                    sOutput = sOutput.Replace("[ACTIONS:DELETE]", String.Empty)
                End If
                If bModEdit Then
                    Dim EditParams() As String = {ParamKeys.ViewType & "=post", "action=te", ParamKeys.ForumId & "=" & ForumId, ParamKeys.TopicId & "=0-0"}
                    sOutput = sOutput.Replace("[ACTIONS:EDIT]", "<a href=""" & NavigateUrl(TabId, "", EditParams) & """><img src=""" & ImagePath & "/images/topic_edit.gif"" border=""0"" style=""vertical-align:middle;"" alt=""[RESX:EditTopic]"" /></a>")
                    sOutput = sOutput.Replace("0-0", "[TOPICID]")
                    sOutput = sOutput.Replace("[AF:QUICKEDITLINK]", "<span class=""af-icon16 af-icon16-gear"" onclick=""amaf_quickEdit([TOPICID]);""></span>")
                Else
                    sOutput = sOutput.Replace("[AF:QUICKEDITLINK]", String.Empty)
                    sOutput = sOutput.Replace("[ACTIONS:EDIT]", String.Empty)
                End If
                If bModMove Then
                    sOutput = sOutput.Replace("[ACTIONS:MOVE]", "<img onclick=""javascript:amaf_openMove([TOPICID]);"" src=""" & ImagePath & "/images/topic_move.gif"" border=""0"" alt=""[RESX:MoveTopic]"" style=""cursor:pointer;vertical-align:middle;"" />")
                Else
                    sOutput = sOutput.Replace("[ACTIONS:MOVE]", String.Empty)
                End If
                If bModLock Then
                    sOutput = sOutput.Replace("[ACTIONS:LOCK]", "<img onclick=""javascript:if(confirm('[RESX:Confirm:Lock]')){amaf_modLock([TOPICID]);};"" src=""" & ImagePath & "/images/topic_lock.gif"" border=""0"" alt=""[RESX:LockTopic]"" style=""cursor:pointer;vertical-align:middle;"" />")
                Else
                    sOutput = sOutput.Replace("[ACTIONS:LOCK]", String.Empty)
                End If
                If bModPin Then
                    sOutput = sOutput.Replace("[ACTIONS:PIN]", "<img onclick=""javascript:if(confirm('[RESX:Confirm:Pin]')){amaf_modPin([TOPICID]);};"" src=""" & ImagePath & "/images/topic_pin.gif"" border=""0""  alt=""[RESX:Pin]"" style=""cursor:pointer;vertical-align:middle;"" />")
                Else
                    sOutput = sOutput.Replace("[ACTIONS:PIN]", String.Empty)
                End If
                sOutput = sOutput.Replace("[FORUMLINK]", "<a href=""" & sForumURL & """>" & ForumName & "</a>")


                Return sOutput
        End Function
        Private Function ParseTopics(ByVal Template As String, ByVal Topics As DataTable, ByVal Section As String) As String
            Dim sOutput As String = Template
            sOutput = TemplateUtils.GetTemplateSection(Template, "[" & Section & "]", "[/" & Section & "]")
            Dim sTopics As String = String.Empty
            Dim MemberListMode As String = MainSettings.MemberListMode
            Dim ProfileVisibility As String = MainSettings.ProfileVisibility
            Dim UserNameDisplay As String = MainSettings.UserNameDisplay
            Dim DisableUserProfiles As Boolean = False
            Dim sLastReply As String = TemplateUtils.GetTemplateSection(sOutput, "[LASTPOST]", "[/LASTPOST]")
            Dim iLength As Integer = 0
            If sLastReply.Contains("[LASTPOSTSUBJECT:") Then
                Dim inStart As Integer = InStr(sLastReply, "[LASTPOSTSUBJECT:") + 17
                Dim inEnd As Integer = InStr(inStart, sLastReply, "]")
                Dim sLength As String = sLastReply.Substring(inStart - 1, inEnd - inStart)
                iLength = CType(sLength, Integer)
            End If
            Dim rowcount As Integer = 0
            LastReplySubjectReplaceTag = "[LASTPOSTSUBJECT:" & iLength.ToString & "]"
            If Topics Is Nothing Then
                sOutput = TemplateUtils.ReplaceSubSection(Template, String.Empty, "[" & Section & "]", "[/" & Section & "]")
                Return sOutput
            End If
            If Topics.Rows.Count > 0 Then
                Dim drTopic As DataRow
                For Each drTopic In Topics.Rows
                    Dim sTopicsTemplate As String = sOutput
                    Dim TopicId As Integer = CInt(drTopic("TopicId"))
                    Dim Subject As String = CStr(drTopic("Subject"))
                    Dim Summary As String = CStr(drTopic("Summary"))
                    Dim Body As String = CStr(drTopic("Body"))
                    'Strip comments

                    Dim AuthorId As Integer = CInt(drTopic("AuthorId"))
                    Dim AuthorName As String = CStr(drTopic("AuthorName")).ToString.Replace("&amp;#", "&#")
                    Dim AuthorFirstName As String = CStr(drTopic("AuthorFirstName")).ToString.Replace("&amp;#", "&#")
                    Dim AuthorLastName As String = CStr(drTopic("AuthorLastName")).ToString.Replace("&amp;#", "&#")
                    Dim AuthorUserName As String = CStr(drTopic("AuthorUserName"))
                    If AuthorUserName = String.Empty Then
                        AuthorUserName = AuthorName
                    End If
                    Dim AuthorDisplayName As String = CStr(drTopic("AuthorDisplayName")).ToString.Replace("&amp;#", "&#")
                    Dim ReplyCount As Integer = CInt(drTopic("ReplyCount"))
                    Dim ViewCount As Integer = CInt(drTopic("ViewCount"))
                    Dim DateCreated As Date = CDate(drTopic("DateCreated"))
                    Dim StatusId As Integer = CInt(drTopic("StatusId"))
                    'LastReply info
                    Dim LastReplyId As Integer = CInt(drTopic("LastReplyId"))
                    Dim LastReplySubject As String = CStr(drTopic("LastReplySubject"))
                    If LastReplySubject = "" Then
                        LastReplySubject = "RE: " & Subject
                    End If
                    Dim LastReplySummary As String = CStr(drTopic("LastReplySummary"))
                    If LastReplySummary = "" Then
                        LastReplySummary = Summary
                    End If
                    Dim LastReplyAuthorId As Integer = CInt(drTopic("LastReplyAuthorId"))
                    Dim LastReplyAuthorName As String = CStr(drTopic("LastReplyAuthorName")).ToString.Replace("&amp;#", "&#")
                    Dim LastReplyFirstName As String = CStr(drTopic("LastReplyFirstName")).ToString.Replace("&amp;#", "&#")
                    Dim LastReplyLastName As String = CStr(drTopic("LastReplyLastName")).ToString.Replace("&amp;#", "&#")
                    Dim LastReplyUserName As String = CStr(drTopic("LastReplyUserName"))
                    Dim LastReplyDisplayName As String = CStr(drTopic("LastReplyDisplayName")).ToString.Replace("&amp;#", "&#")
                    Dim LastReplyDate As Date = CDate(drTopic("LastReplyDate"))
                    Dim UserLastTopicRead As Integer = CInt(drTopic("UserLastTopicRead"))
                    Dim UserLastReplyRead As Integer = CInt(drTopic("UserLastReplyRead"))
                    Dim isLocked As Boolean = CBool(drTopic("IsLocked"))
                    Dim isPinned As Boolean = CBool(drTopic("IsPinned"))
                    Dim TopicURL As String = drTopic("TopicURL").ToString
                    Dim topicData As String = drTopic("TopicData").ToString
                    If isLocked Then
                        sTopicsTemplate = sTopicsTemplate.Replace("[RESX:LockTopic]", "[RESX:UnLockTopic]")
                        sTopicsTemplate = sTopicsTemplate.Replace("[RESX:Confirm:Lock]", "[RESX:Confirm:UnLock]")

                    End If
                    If isPinned Then
                        sTopicsTemplate = sTopicsTemplate.Replace("[RESX:PinTopic]", "[RESX:UnPinTopic]")
                        sTopicsTemplate = sTopicsTemplate.Replace("[RESX:Confirm:Pin]", "[RESX:Confirm:UnPin]")

                    End If

                    If String.IsNullOrEmpty(topicData) Then
                        sTopicsTemplate = TemplateUtils.ReplaceSubSection(sTopicsTemplate, String.Empty, "[AF:PROPERTIES]", "[/AF:PROPERTIES]")
                    Else
                        Dim sPropTemplate As String = TemplateUtils.GetTemplateSection(sTopicsTemplate, "[AF:PROPERTIES]", "[/AF:PROPERTIES]")
                        Dim sProps As String = String.Empty
                        Dim xDoc As New XmlDocument
                        xDoc.LoadXml(topicData)
                        If Not xDoc Is Nothing Then
                            Dim xRoot As System.Xml.XmlNode = xDoc.DocumentElement
                            Dim xNodeList As System.Xml.XmlNodeList = xRoot.SelectNodes("//properties/property")
                            If xNodeList.Count > 0 Then
                                Dim i As Integer = 0
                                For i = 0 To xNodeList.Count - 1
                                    Dim tmp As String = sPropTemplate
                                    Dim pName As String = Utilities.HTMLDecode(xNodeList(i).ChildNodes.Item(0).InnerText)
                                    Dim pValue As String = Utilities.HTMLDecode(xNodeList(i).ChildNodes.Item(1).InnerText)
                                    tmp = tmp.Replace("[AF:PROPERTY:LABEL]", Utilities.GetSharedResource("[RESX:" & pName & "]"))
                                    tmp = tmp.Replace("[AF:PROPERTY:VALUE]", pValue)
                                    sTopicsTemplate = sTopicsTemplate.Replace("[AF:PROPERTY:" & pName & ":LABEL]", Utilities.GetSharedResource("[RESX:" & pName & "]"))
                                    sTopicsTemplate = sTopicsTemplate.Replace("[AF:PROPERTY:" & pName & ":VALUE]", pValue)
                                    Dim pValueKey As String = String.Empty
                                    If Not String.IsNullOrEmpty(pValue) Then
                                        pValueKey = Utilities.CleanName(pValue).ToLowerInvariant
                                    End If
                                    sTopicsTemplate = sTopicsTemplate.Replace("[AF:PROPERTY:" & pName & ":VALUEKEY]", pValueKey)
                                    sProps &= tmp
                                Next
                            End If
                            If sTopicsTemplate.Contains("[AF:PROPERTY:") Then

                            End If
                        End If
                        sTopicsTemplate = TemplateUtils.ReplaceSubSection(sTopicsTemplate, sProps, "[AF:PROPERTIES]", "[/AF:PROPERTIES]")

                    End If


                    sTopicsTemplate = sTopicsTemplate.Replace("[TOPICID]", TopicId.ToString)
                    sTopicsTemplate = sTopicsTemplate.Replace("[AUTHORID]", AuthorId.ToString)
                    sTopicsTemplate = sTopicsTemplate.Replace("[FORUMID]", ForumId.ToString)
                    sTopicsTemplate = sTopicsTemplate.Replace("[USERID]", UserId.ToString)
                    sTopicsTemplate = sTopicsTemplate.Replace("[POSTICON]", GetIcon(UserLastTopicRead, UserLastReplyRead, TopicId, LastReplyId, drTopic("TopicIcon").ToString, isPinned, isLocked))
                    If Not String.IsNullOrEmpty(Summary) Then
                        If Not Utilities.HasHTML(Summary) Then
                            Summary = Summary.Replace(vbCrLf, "<br />")
                        End If
                    End If

                    Dim sBodyTitle As String = String.Empty
                    If bRead Then
                        sBodyTitle = GetTitle(Body, AuthorId)
                    End If
                    sTopicsTemplate = sTopicsTemplate.Replace("[BODYTITLE]", sBodyTitle)
                    sTopicsTemplate = sTopicsTemplate.Replace("[BODY]", GetBody(Body, AuthorId))
                    Dim BodyLength As Integer = -1
                    Dim BodyTrim As String = String.Empty

                    If Template.Contains("[BODY:") Then
                        Dim inStart As Integer = InStr(Template, "[BODY:") + 5
                        Dim inEnd As Integer = InStr(inStart, Template, "]") - 1
                        Dim sLength As String = Template.Substring(inStart, inEnd - inStart)
                        BodyLength = CType(sLength, Integer)
                        BodyTrim = "[BODY:" & BodyLength.ToString & "]"
                    End If
                    Dim BodyPlain As String = String.Empty
                    If String.IsNullOrEmpty(Summary) And sTopicsTemplate.Contains("[SUMMARY]") And String.IsNullOrEmpty(BodyTrim) Then
                        BodyTrim = "[BODY:250]"
                        BodyLength = 250
                    End If
                    If Not BodyTrim = String.Empty Then
                        BodyPlain = Body.Replace("<br>", vbCrLf)
                        BodyPlain = BodyPlain.Replace("<br />", vbCrLf)
                        BodyPlain = Utilities.StripHTMLTag(BodyPlain)
                        If BodyLength > 0 And BodyPlain.Length > BodyLength Then
                            BodyPlain = BodyPlain.Substring(0, BodyLength)
                        End If
                        BodyPlain = BodyPlain.Replace(vbCrLf, "<br />")
                        sTopicsTemplate = sTopicsTemplate.Replace(BodyTrim, BodyPlain)
                    End If
                    If String.IsNullOrEmpty(Summary) Then
                        Summary = BodyPlain
                        Summary = Summary.Replace("<br />", "  ")
                    End If
                    sTopicsTemplate = sTopicsTemplate.Replace("[SUMMARY]", Summary)
                    Dim sPollImage As String = ""
                    If CInt(drTopic("TopicType")) = 1 Then
                        sPollImage = "<img src=""" & MyThemePath & "/images/poll.png"" style=""vertical-align:middle;"" alt=""[RESX:Poll]"" />"
                    End If
                    Dim sTopicURL As String = String.Empty
                    Dim ctlUtils As New ControlUtils
                    sTopicURL = ctlUtils.BuildUrl(ForumTabId, ForumModuleId, ForumInfo.ForumGroup.PrefixURL, ForumInfo.PrefixURL, ForumGroupId, ForumId, TopicId, TopicURL, -1, -1, String.Empty, 1, SocialGroupId)

                    Dim sLastReplyURL As String = NavigateUrl(TabId, "", New String() {ParamKeys.TopicId & "=" & TopicId, ParamKeys.ContentJumpId & "=" & LastReplyId})
                    If Not String.IsNullOrEmpty(sTopicURL) Then
                        If sTopicURL.EndsWith("/") Then
                            sLastReplyURL = sTopicURL & "?" & ParamKeys.ContentJumpId & "=" & LastReplyId
                        End If
                    End If
                    Dim sLastReadURL As String = String.Empty
                    Dim sUserJumpUrl As String = String.Empty
                    If UserLastReplyRead > 0 Then
                        sLastReadURL = NavigateUrl(TabId, "", New String() {ParamKeys.ForumId & "=" & ForumId, ParamKeys.TopicId & "=" & TopicId, ParamKeys.ViewType & "=topic", ParamKeys.FirstNewPost & "=" & UserLastReplyRead})
                        If MainSettings.UseShortUrls Then
                            sLastReadURL = NavigateUrl(TabId, "", New String() {ParamKeys.TopicId & "=" & TopicId, ParamKeys.FirstNewPost & "=" & UserLastReplyRead})
                        End If
                        If sTopicURL.EndsWith("/") Then
                            sLastReadURL = sTopicURL & "?" & ParamKeys.FirstNewPost & "=" & UserLastReplyRead
                        End If
                    End If

                    If UserPrefJumpLastPost And sLastReadURL <> String.Empty Then
                        sTopicURL = sLastReadURL
                        sUserJumpUrl = sLastReadURL
                    End If
                    If UserId = -1 Or LastReplyId = 0 Then
                        sTopicsTemplate = sTopicsTemplate.Replace("[AF:ICONLINK:LASTREAD]", String.Empty)
                        sTopicsTemplate = sTopicsTemplate.Replace("[AF:URL:LASTREAD]", String.Empty)
                    Else
                        If (UserLastTopicRead >= TopicId Or UserLastTopicRead = 0) And (UserLastReplyRead >= LastReplyId Or UserLastReplyRead = 0) Then
                            sTopicsTemplate = sTopicsTemplate.Replace("[AF:ICONLINK:LASTREAD]", String.Empty)
                            sTopicsTemplate = sTopicsTemplate.Replace("[AF:URL:LASTREAD]", String.Empty)
                        Else
                            sTopicsTemplate = sTopicsTemplate.Replace("[AF:ICONLINK:LASTREAD]", "<a href=""" & sLastReadURL & """ rel=""nofollow""><img src=""" & MyThemePath & "/images/miniarrow_down.png"" style=""vertical-align:middle;"" alt=""[RESX:JumpToLastRead]"" border=""0"" class=""afminiarrow"" /></a>")
                            sTopicsTemplate = sTopicsTemplate.Replace("[AF:URL:LASTREAD]", sLastReadURL)
                        End If

                    End If
                    If LastReplyId > 0 And bRead Then
                        sTopicsTemplate = sTopicsTemplate.Replace("[AF:ICONLINK:LASTREPLY]", "<a href=""" & sLastReplyURL & """ rel=""nofollow""><img src=""" & MyThemePath & "/images/miniarrow_right.png"" style=""vertical-align:middle;"" alt=""[RESX:JumpToLastReply]"" border=""0"" class=""afminiarrow"" /></a>")
                        sTopicsTemplate = sTopicsTemplate.Replace("[AF:URL:LASTREPLY]", sLastReplyURL)
                        sTopicsTemplate = sTopicsTemplate.Replace("[AF:UI:MINIPAGER]", GetSubPages(TabId, ModuleId, ReplyCount, ForumId, TopicId))
                    Else
                        sTopicsTemplate = sTopicsTemplate.Replace("[AF:ICONLINK:LASTREPLY]", String.Empty)
                        sTopicsTemplate = sTopicsTemplate.Replace("[AF:URL:LASTREPLY]", String.Empty)
                        sTopicsTemplate = sTopicsTemplate.Replace("[AF:UI:MINIPAGER]", String.Empty)
                    End If

                    sTopicsTemplate = sTopicsTemplate.Replace("[TOPICURL]", sTopicURL)
                    Subject = Utilities.StripHTMLTag(Subject)
                    Subject = Subject.Replace("&#91;", "[")
                    Subject = Subject.Replace("&#93;", "]")
                    sTopicsTemplate = sTopicsTemplate.Replace("[SUBJECT]", sPollImage & Subject)
                    'sTopicsTemplate = sTopicsTemplate.Replace("[SUBJECTLINK]", sPollImage & GetTopic(ModuleId, TabId, ForumId, TopicId, Subject, sBodyTitle, UserId, AuthorId, ReplyCount, -1, sUserJumpUrl))
                    sTopicsTemplate = sTopicsTemplate.Replace("[SUBJECTLINK]", sPollImage & GetTopic(ModuleId, TabId, ForumId, TopicId, Subject, sBodyTitle, UserId, AuthorId, ReplyCount, -1, sTopicURL))


                    sTopicsTemplate = sTopicsTemplate.Replace("[STARTEDBY]", UserProfiles.GetDisplayName(ModuleId, ProfileVisibility, bModApprove, AuthorId, UserNameDisplay, AuthorUserName, AuthorFirstName, AuthorLastName, AuthorDisplayName).ToString.Replace("&amp;#", "&#"))
                    sTopicsTemplate = sTopicsTemplate.Replace("[DATECREATED]", GetDate(DateCreated))
                    sTopicsTemplate = sTopicsTemplate.Replace("[REPLIES]", ReplyCount.ToString)
                    sTopicsTemplate = sTopicsTemplate.Replace("[VIEWS]", ViewCount.ToString)
                    sTopicsTemplate = sTopicsTemplate.Replace("[ROWCSS]", GetRowCSS(UserLastTopicRead, UserLastReplyRead, TopicId, LastReplyId, rowcount))

                    If CInt(drTopic("TopicRating")) = 0 Then
                        sTopicsTemplate = sTopicsTemplate.Replace("[POSTRATINGDISPLAY]", String.Empty)
                    Else
                        Dim sRatingImage As String
                        'sRatingImage = "<img src=""" & MyThemePath & "/yellow_star_0" & drTopic("TopicRating").ToString & ".gif"" alt=""" & drTopic("TopicRating").ToString & """ />"
                        sRatingImage = "<span class=""af-rater rate" & drTopic("TopicRating").ToString & """>&nbsp;</span>"
                        sTopicsTemplate = sTopicsTemplate.Replace("[POSTRATINGDISPLAY]", sRatingImage)
                    End If

                    If sTopicsTemplate.Contains("[STATUS]") Then
                        Dim sImg As String = String.Empty
                        If StatusId = -1 Then
                            sTopicsTemplate = sTopicsTemplate.Replace("[STATUS]", String.Empty)
                        Else
                            sImg = "<img alt=""[RESX:PostStatus" & StatusId.ToString & "]"" src=""" & MyThemePath & "/images/status" & StatusId.ToString & ".png"" />"
                        End If
                        sTopicsTemplate = sTopicsTemplate.Replace("[STATUS]", sImg)
                    End If

                    If sTopicsTemplate.Contains("[LASTPOST]") Then
                        If LastReplyId = 0 Then
                            sTopicsTemplate = TemplateUtils.ReplaceSubSection(sTopicsTemplate, GetDate(LastReplyDate), "[LASTPOST]", "[/LASTPOST]")
                        Else
                            Dim sLastReplyTemp As String = sLastReply
                            If bRead Then
                                sLastReplyTemp = sLastReplyTemp.Replace("[AF:ICONLINK:LASTREPLY]", "<a href=""" & sLastReplyURL & """ rel=""nofollow""><img src=""" & MyThemePath & "/images/miniarrow_right.png"" style=""vertical-align:middle;"" alt=""[RESX:JumpToLastReply]"" border=""0"" class=""afminiarrow"" /></a>")
                                sLastReplyTemp = sLastReplyTemp.Replace("[AF:URL:LASTREPLY]", sLastReplyURL)
                            Else
                                sLastReplyTemp = sLastReplyTemp.Replace("[AF:ICONLINK:LASTREPLY]", String.Empty)
                                sLastReplyTemp = sLastReplyTemp.Replace("[AF:URL:LASTREPLY]", String.Empty)
                            End If

                            sLastReplyTemp = sLastReplyTemp.Replace(LastReplySubjectReplaceTag, Utilities.GetLastPostSubject(LastReplyId, TopicId, ForumId, TabId, LastReplySubject, iLength, PageSize, ReplyCount, bRead))
                            'sLastReplyTemp = sLastReplyTemp.Replace("[RESX:BY]", Utilities.GetSharedResource("By.Text"))
                            If LastReplyAuthorId > 0 Then
                                sLastReplyTemp = sLastReplyTemp.Replace("[LASTPOSTDISPLAYNAME]", UserProfiles.GetDisplayName(ModuleId, ProfileVisibility, bModApprove, LastReplyAuthorId, UserNameDisplay, LastReplyUserName, LastReplyFirstName, LastReplyLastName, LastReplyDisplayName).ToString.Replace("&amp;#", "&#"))
                            Else
                                sLastReplyTemp = sLastReplyTemp.Replace("[LASTPOSTDISPLAYNAME]", LastReplyAuthorName)
                            End If

                            sLastReplyTemp = sLastReplyTemp.Replace("[LASTPOSTDATE]", GetDate(LastReplyDate))
                            sTopicsTemplate = TemplateUtils.ReplaceSubSection(sTopicsTemplate, sLastReplyTemp, "[LASTPOST]", "[/LASTPOST]")
                        End If
                    End If

                    sTopics &= sTopicsTemplate
                    rowcount += 1
                Next
                sOutput = TemplateUtils.ReplaceSubSection(Template, sTopics, "[" & Section & "]", "[/" & Section & "]")
            Else
                sOutput = TemplateUtils.ReplaceSubSection(Template, String.Empty, "[" & Section & "]", "[/" & Section & "]")
            End If

            Return sOutput
        End Function
        Private Sub BuildPager()
            If TopicRowCount > 0 Then
                Dim Pager1 As DotNetNuke.Modules.ActiveForums.Controls.PagerNav
                Pager1 = CType(Me.FindControl("Pager1"), DotNetNuke.Modules.ActiveForums.Controls.PagerNav)

                Dim Pager2 As DotNetNuke.Modules.ActiveForums.Controls.PagerNav = Nothing
                Dim obj As Object = Me.FindControl("Pager2")
                If Not obj Is Nothing Then
                    Pager2 = CType(obj, DotNetNuke.Modules.ActiveForums.Controls.PagerNav)
                End If

                Dim intPages As Integer
                If Not Pager1 Is Nothing Then
                    intPages = CType(System.Math.Ceiling(TopicRowCount / PageSize), Integer)
                    Pager1.PageCount = intPages
                    Pager1.PageMode = PagerNav.Mode.Links
                    If Not String.IsNullOrEmpty(ForumInfo.PrefixURL) And MainSettings.URLRewriteEnabled Then
                        If Not String.IsNullOrEmpty(MainSettings.PrefixURLBase) Then
                            Pager1.BaseURL = "/" & MainSettings.PrefixURLBase
                        End If
                        Pager1.BaseURL &= "/" & ForumInfo.ForumGroup.PrefixURL & "/" & ForumInfo.PrefixURL & "/"
                        Pager1.PageMode = PagerNav.Mode.Links
                    End If
                    Pager1.CurrentPage = PageId
                    Pager1.TabID = CType(Request.Params("TabId"), Integer)
                    Pager1.ForumID = ForumId
                    Pager1.UseShortUrls = MainSettings.UseShortUrls
                    Pager1.PageText = Utilities.GetSharedResource("[RESX:Page]")
                    Pager1.OfText = Utilities.GetSharedResource("[RESX:PageOf]")
                    Pager1.View = Views.Topics
                    If Not Request.Params("afsort") Is Nothing Then
                        Dim Params As String() = {"afsort=" & Request.Params("afsort"), "afcol=" & Request.Params("afcol")}
                        Pager1.Params = Params
                        If Not Pager2 Is Nothing Then
                            Pager2.Params = Params
                        End If

                    End If
                End If


                If Not Pager2 Is Nothing Then
                    Pager2.PageMode = Modules.ActiveForums.Controls.PagerNav.Mode.Links ' DotNetNuke.Modules.ActiveForums.Controls.Pager.Mode.CallBack
                    If Not String.IsNullOrEmpty(ForumInfo.PrefixURL) And MainSettings.URLRewriteEnabled Then
                        If Not String.IsNullOrEmpty(MainSettings.PrefixURLBase) Then
                            Pager2.BaseURL = "/" & MainSettings.PrefixURLBase
                        End If
                        Pager2.BaseURL &= "/" & ForumInfo.ForumGroup.PrefixURL & "/" & ForumInfo.PrefixURL & "/"
                        Pager2.PageMode = PagerNav.Mode.Links
                    End If
                    Pager2.UseShortUrls = MainSettings.UseShortUrls
                    Pager2.PageCount = intPages
                    Pager2.CurrentPage = PageId
                    Pager2.TabID = CType(Request.Params("TabId"), Integer)
                    Pager2.ForumID = ForumId
                    Pager2.PageText = Utilities.GetSharedResource("[RESX:Page]")
                    Pager2.OfText = Utilities.GetSharedResource("[RESX:PageOf]")
                    Pager2.View = Views.Topics
                End If
            End If


        End Sub
        Private Function GetIcon(ByVal LastTopicRead As Integer, ByVal LastReplyRead As Integer, ByVal TopicId As Integer, ByVal ReplyId As Integer, ByVal Icon As String, Optional ByVal Pinned As Boolean = False, Optional ByVal Locked As Boolean = False) As String
            If Icon = String.Empty Then
                If Pinned And Locked Then
                    Return "<img src=""" & MyThemePath & "/images/topic_pinlocked.png"" alt=""[RESX:PinnedLocked]"" />"
                ElseIf Pinned Then
                    Return "<img src=""" & MyThemePath & "/images/topic_pin.png"" alt=""[RESX:Pinned]"" />"
                ElseIf Locked Then
                    Return "<img src=""" & MyThemePath & "/emoticons/lock.gif"" alt=""[RESX:Locked]"" />"
                Else
                    If Not Request.IsAuthenticated Then
                        Return "<img src=""" & MyThemePath & "/emoticons/document.gif"" alt=""[RESX:TopicRead]"" />"
                    Else
                        If LastTopicRead = 0 Then
                            Return "<img src=""" & MyThemePath & "/emoticons/document_new.gif"" alt=""[RESX:TopicNew]"" />"
                        ElseIf LastTopicRead > 0 And LastReplyRead < ReplyId Then
                            Return "<img src=""" & MyThemePath & "/emoticons/document_new.gif"" alt=""[RESX:TopicNew]"" />"
                        Else
                            Return "<img src=""" & MyThemePath & "/emoticons/document.gif"" alt=""[RESX:TopicRead]"" />"
                        End If
                    End If

                End If
            Else
                Return "<img src=""" & MyThemePath & "/emoticons/" & Icon & """ alt=""" & Icon & """ />"
            End If
        End Function
        Private Function GetTitle(ByVal Body As String, ByVal AuthorId As Integer) As String
            If bRead Or AuthorId = Me.UserId Then
                Body = Replace(Body, "<br>", vbCrLf)
                Body = Replace(Body, "[", "&#91")
                Body = Replace(Body, "]", "&#93")
                Body = Utilities.StripHTMLTag(Body)
                Body = Left(Body, 500) & "..."
                Body = Replace(Body, """", "'")
                Body = Replace(Body, "?", String.Empty)
                Body = Replace(Body, "+", String.Empty)
                Body = Replace(Body, "%", String.Empty)
                Body = Replace(Body, "#", String.Empty)
                Body = Replace(Body, "@", String.Empty)
                Return Body.Trim
            Else
                Return String.Empty
            End If

        End Function
        Private Function GetBody(ByVal Body As String, ByVal AuthorId As Integer) As String
            If bRead Or AuthorId = Me.UserId Then
                Body = Replace(Body, "[", "&#91")
                Body = Replace(Body, "]", "&#93")
                Return Body
            Else
                Return String.Empty
            End If

        End Function
        Private Function GetTopic(ByVal ModuleID As Integer, ByVal TabID As Integer, ByVal ForumID As Integer, ByVal PostID As Integer, ByVal Subject As String, ByVal BodyTitle As String, ByVal UserID As Integer, ByVal PostUserID As Integer, ByVal Replies As Integer, ByVal ForumOwnerID As Integer, ByVal sLink As String) As String
            Dim sOut As String
            'Subject = Replace(Subject, "[", "&#91")
            'Subject = Replace(Subject, "]", "&#93")
            Subject = Utilities.StripHTMLTag(Subject)
            Subject = Subject.Replace("""", String.Empty)
            Subject = Subject.Replace("'", String.Empty)
            Subject = Subject.Replace("#", String.Empty)
            Subject = Subject.Replace("%", String.Empty)
            ' Subject = Subject.Replace("?", String.Empty)
            Subject = Subject.Replace("+", String.Empty)

            If bRead Then
                If sLink = String.Empty Then
                    Dim Params As String() = {ParamKeys.ForumId & "=" & ForumID, ParamKeys.TopicId & "=" & PostID, ParamKeys.ViewType & "=" & Views.Topic}
                    If MainSettings.UseShortUrls Then
                        Params = New String() {ParamKeys.TopicId & "=" & PostID}
                    End If
                    sOut = "<a title=""" & BodyTitle & """ href=""" & NavigateUrl(TabID, "", Params) & """>" & Subject & "</a>"
                Else
                    sOut = "<a title=""" & BodyTitle & """ href=""" & sLink & """>" & Subject & "</a>"
                End If

                'sOut = sOut & GetSubPages(TabID, ModuleID, Replies, ForumID, PostID)
            Else
                sOut = Subject
            End If
            Return sOut
        End Function
        Private Function GetSubPages(ByVal TabID As Integer, ByVal ModuleID As Integer, ByVal Replies As Integer, ByVal ForumID As Integer, ByVal PostID As Integer) As String
            Dim i As Integer
            Dim sOut As String = ""

            If Replies + 1 > PageSize Then
                'sOut = "<div class=""afpagermini"">" & GetSharedResource("SubPages.Text") & "&nbsp;"
                sOut = "<div class=""afpagermini"">(<img src=""" & MyThemePath & "/images/icon_multipage.png"" alt=""[RESX:MultiPageTopic]"" style=""vertical-align:middle;"" />"
                'Jump to pages
                Dim intPostPages As Integer
                intPostPages = CType(System.Math.Ceiling((Replies + 1) / PageSize), Integer)
                If intPostPages > 3 Then
                    For i = 1 To 3
                        If UseAjax Then
                            Dim Params As String() = {ParamKeys.ForumId & "=" & ForumID, ParamKeys.TopicId & "=" & PostID, ParamKeys.ViewType & "=" & Views.Topic}
                            If MainSettings.UseShortUrls Then
                                Params = New String() {ParamKeys.TopicId & "=" & PostID}
                            End If
                            If i > 1 Then
                                Params = Utilities.AddParams(ParamKeys.PageJumpId & "=" & i, Params)
                            End If
                            sOut &= "<a href=""" & NavigateUrl(TabID, "", Params) & """>" & i & "</a>&nbsp;"
                        Else
                            Dim Params As String() = {ParamKeys.ForumId & "=" & ForumID, ParamKeys.TopicId & "=" & PostID, ParamKeys.ViewType & "=" & Views.Topic}
                            If MainSettings.UseShortUrls Then
                                Params = New String() {ParamKeys.TopicId & "=" & PostID}
                            End If
                            If i > 1 Then
                                Params = Utilities.AddParams(ParamKeys.PageId & "=" & i, Params)
                            End If
                            sOut &= "<a href=""" & NavigateUrl(TabID, "", Params) & """>" & i & "</a>&nbsp;"
                        End If

                    Next
                    If intPostPages > 4 Then
                        sOut &= "...&nbsp;"
                    End If
                    If UseAjax Then
                        'sOut &= "<span class=""afpagerminiitem"" onclick=""javascript:afPageJump(" & intPostPages & ");"">" & intPostPages & "</span>&nbsp;"
                        Dim Params2 As String() = {ParamKeys.ForumId & "=" & ForumID, ParamKeys.TopicId & "=" & PostID, ParamKeys.ViewType & "=" & Views.Topic, ParamKeys.PageJumpId & "=" & intPostPages}
                        If MainSettings.UseShortUrls Then
                            Params2 = New String() {ParamKeys.TopicId & "=" & PostID, ParamKeys.PageJumpId & "=" & intPostPages}
                        End If

                        sOut &= "<a href=""" & NavigateUrl(TabID, "", Params2) & """>" & intPostPages & "</a>&nbsp;"
                    Else
                        Dim Params2 As String() = {ParamKeys.ForumId & "=" & ForumID, ParamKeys.TopicId & "=" & PostID, ParamKeys.ViewType & "=" & Views.Topic, ParamKeys.PageId & "=" & intPostPages}
                        If MainSettings.UseShortUrls Then
                            Params2 = New String() {ParamKeys.TopicId & "=" & PostID, ParamKeys.PageId & "=" & intPostPages}
                        End If
                        sOut &= "<a href=""" & NavigateUrl(TabID, "", Params2) & """>" & intPostPages & "</a>&nbsp;"
                    End If


                Else
                    For i = 1 To intPostPages
                        If UseAjax Then
                            'sOut &= "<span class=""afpagerminiitem"" onclick=""javascript:afPageJump(" & i & ");"">" & i & "</span>&nbsp;"
                            Dim Params As String() = {ParamKeys.ForumId & "=" & ForumID, ParamKeys.TopicId & "=" & PostID, ParamKeys.ViewType & "=" & Views.Topic}
                            If MainSettings.UseShortUrls Then
                                Params = New String() {ParamKeys.TopicId & "=" & PostID}
                            End If
                            If i > 1 Then
                                Params = Utilities.AddParams(ParamKeys.PageJumpId & "=" & i, Params)
                            End If
                            sOut &= "<a href=""" & NavigateUrl(TabID, "", Params) & """>" & i & "</a>&nbsp;"
                        Else
                            Dim Params As String() = {ParamKeys.ForumId & "=" & ForumID, ParamKeys.TopicId & "=" & PostID, ParamKeys.ViewType & "=" & Views.Topic}
                            If MainSettings.UseShortUrls Then
                                Params = New String() {ParamKeys.TopicId & "=" & PostID}
                            End If
                            If i > 1 Then
                                Params = Utilities.AddParams(ParamKeys.PageId & "=" & i, Params)
                            End If
                            sOut &= "<a href=""" & NavigateUrl(TabID, "", Params) & """>" & i & "</a>&nbsp;"
                        End If

                    Next
                End If

                sOut &= ")</div>"
            End If
            Return sOut
        End Function
        Private Function GetRowCSS(ByVal LastTopicRead As Integer, ByVal LastReplyRead As Integer, ByVal TopicId As Integer, ByVal ReplyId As Integer, ByVal RowCount As Integer) As String
            Dim isRead As Boolean = False
            If LastTopicRead >= TopicId And LastReplyRead >= ReplyId Then
                isRead = True
            End If
            If Not Request.IsAuthenticated Then
                isRead = True
            End If
            If isRead = True Then
                If RowCount Mod 2 = 0 Then
                    Return "aftopicrow"
                Else
                    Return "aftopicrowalt"
                End If
            Else
                If RowCount Mod 2 = 0 Then
                    Return "aftopicrownew"
                Else
                    Return "aftopicrownewalt"
                End If
            End If
        End Function


        Private Sub ctlModal_Callback(ByVal sender As Object, ByVal e As Modules.ActiveForums.Controls.CallBackEventArgs) Handles ctlModal.Callback
            Select Case e.Parameters(0).ToLowerInvariant
                Case "load"
                    ctlModal.ModalContent.Controls.Clear()
                    Dim ctlPath As String = String.Empty
                    Dim ctrl As String = e.Parameters(1).ToLowerInvariant
                    Dim ctlParams As String = e.Parameters(2).ToLowerInvariant
                    Session("modal_View") = ctrl
                    Session("modal_options") = ctlParams
                    LoadModal(ctrl, ctlParams)
                Case "clear"
                    ctlModal.ModalContent.Controls.Clear()
                    Session("modal_View") = Nothing
                    Session("modal_options") = Nothing
            End Select
            ctlModal.ModalContent.RenderControl(e.Output)
        End Sub
        Private Sub LoadModal(ByVal ctrl As String, Optional ByVal params As String = "")
            ctlModal.ModalContent.Controls.Clear()
            Dim ctlPath As String = String.Empty
            Session("modal_View") = ctrl
            Session("modal_options") = params
            ctlPath = "~/DesktopModules/activeforums/controls/af_" & ctrl & ".ascx"
            Dim ctl As ForumBase = CType(LoadControl(ctlPath), ForumBase)
            ctl.ID = ctrl
            ctl.ModuleConfiguration = Me.ModuleConfiguration

            If Not params = String.Empty Then
                ctl.Params = params
            End If
            If Not ctlModal.ModalContent.Controls.Contains(ctl) Then
                ctlModal.ModalContent.Controls.Add(ctl)
            End If
        End Sub
        Private Function CheckControls(ByVal template As String) As String
            If String.IsNullOrEmpty(template) Then
                Return String.Empty
            End If
            If Not template.Contains("<%@ Register TagPrefix=""ac"" Namespace=""DotNetNuke.Modules.ActiveForums.Controls"" Assembly=""DotNetNuke.Modules.ActiveForums"" %>") Then
                template = "<%@ Register TagPrefix=""ac"" Namespace=""DotNetNuke.Modules.ActiveForums.Controls"" Assembly=""DotNetNuke.Modules.ActiveForums"" %>" & template
            End If
            If ForumId > 0 Then
                If Not ForumInfo.Security Is Nothing Then
                    If Permissions.HasAccess(ForumInfo.Security.Create, ForumUser.UserRoles) Then
                        Dim Params() As String = {}
                        If SocialGroupId > 0 Then
                            Params = {"GroupId=" & SocialGroupId, ParamKeys.ViewType & "=post", ParamKeys.ForumId & "=" & ForumId}
                        Else
                            Params = {ParamKeys.ViewType & "=post", ParamKeys.ForumId & "=" & ForumId}
                        End If

                        template = template.Replace("[ADDTOPIC]", "<a href=""" & NavigateUrl(TabId, "", Params) & """ class=""dnnPrimaryAction"">[RESX:AddTopic]</a>")
                    End If
                End If
            End If


            Return template
        End Function
    End Class
End Namespace

